define(["PDUtilDir/grid","PDUtilDir/searchBlock","PDUtilDir/slidebar","PDUtilDir/fileupload/multiFileUpload","PDUtilDir/inputSelect",
        "PDUtilDir/tool", "PDUtilDir/util",
        'PDAppDir/properties',"wx","PicView","css!picViewCss"],

    function(Grid,SearchBlock,Slidebar,MFU,inputSelect,Tool,Util,Properties,wx){

    function openDemoAForm(){
        openForm({
            body:"static/core/examples/demos/form/form/form.html",
            ctrl:"static/core/examples/demos/form/form/formCtrl",
            uuid:"uuid"
        });
    }
    function initGrid(param){

        SearchBlock.init('searchBlockId');

        //初始化
        grid = Grid({
            id:"DemoGirdDivId",
            pageSize:10,
            index:true,
            multi:true,
            pagination : true,
            cache:false,
            layout:[
                {name:"景点名称",field:"name",sort:true,click:function(e){
                        var data = e.data.row;
                        editSpot(data);
                }},
                {name:"描述",field:"description"},
                {name:"开放时间",field:"openTime",width:"10%"},
                {name:"等级",field:"level",sort:true,format:function (obj) {
                        // console.log(obj.row.level)
                        var level = obj.row.level;
                        if (level==="D_SPOT_LEVEL_THREE"){
                            return "3星"
                        }else if (level==="D_SPOT_LEVEL_FOUR"){
                            return "4星"
                        }else if (level==="D_SPOT_LEVEL_FIVE"){
                            return "5星"
                        }
                    }},
                {name:"添加门票",field:"null",format:function(obj){
                	return "添加门票"
                },click:function(obj){
                    addTicket(obj.data.row.id);
                    spotName = obj.data.row.name;
                }},
                {name:"分享",field:"null",format:function(obj){
                        return "分享"
                    },click:function(obj){
                        share();
                    }}
            ],
            toolbar:[
                {name:"添加",icon:"fa fa-plus-circle",callback:function(event){
                        editSpot(null);
                }},
                {name:"删除",icon:"fa fa-trash-o",callback:function(event){
                        deleteBySelectIds();
                    }},
                {name:"查询",icon:"fa fa-search",callback:function(event){
                        initGrid(getQueryParam());
                }}
            ],
            data:{ type:"URL",value:getServer()+"/flea/hclv/spot/selectMySpotByDeptId.htmls"},
            queryParam:param
        });
    }
    var share = function () {
        var url = location.href.split('#');//url不能写死
        $.ajax({
            type : "POST",
            url : "/flea/wx/share.htmls",
            data:{url:JSON.stringify(url)},
            success : function(data) {
                wx.config({
                        debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                        appId: data.data.appId, // 必填，公众号的唯一标识
                        timestamp:  data.data.timestamp, // 必填，生成签名的时间戳
                        nonceStr:  data.data.nonceStr, // 必填，生成签名的随机串
                        signature:  data.data.signature,// 必填，签名
                        jsApiList: ['onMenuShareAppMessage','onMenuShareTimeline'] // 必填，需要使用的JS接口列表
                });
                wx.ready(function(){
                    // console.log("wx.ready");
                    //分享给朋友
                    wx.onMenuShareAppMessage({
                        title: "分享标题", // 分享标题
                        desc: "分享描述", // 分享描述
                        link: "http://www.imflea.cn/hclv-web", // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl:"分享图标s", // 分享图标s
                        type: 'link', // 分享类型,music、video或link，不填默认为link
                        dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
                        success: function () {
                            // 用户确认分享后执行的回调函数
                            // console.log("success");
	    					 // alert("success");

                        },
                        cancel: function () {
                            // 用户取消分享后执行的回调函数
                            // console.log("fail")
	    					 // alert("fail");
                        }
                    });
                    //分享给朋友圈
                    wx.onMenuShareTimeline({
                        title: "分享标题", // 分享标题
                        link: "http://www.imflea.cn/hclv-web", // 分享链接，该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                        imgUrl: "分享图标", // 分享图标
                        success: function () {
                            // 用户确认分享后执行的回调函数
                            alert("分享给朋友圈")
                        }
                    });
                });
                wx.error(function(res){
                    // console.log('err', res)
                });
            },
            error: function(xhr, status, error) {
                alert(status);
                alert(xhr.responseText);
            }
        })
    };
    //初始化门票表格
    var initTicketGrid = function (data) {
        ticketGrid = Grid({
            id: "ticketGird",
            pageSize: 10,
            index: true,
            multi: true,
            pagination: true,
            cache: false,
            layout: [
                {
                    name: "门票代码", field: "code", sort: true, click: function (e) {
                        var row = e.data.row;
                        editSpotTicket(row);
                    }
                },
                {
                    name: "类型", field: "type", format: function (e) {
                        var type = e.row.type;
                        if (type === "D_SPOT_TICKET_TYPE_ADULT") {
                            return "成人票";
                        } else if (type === "D_SPOT_TICKET_TYPE_CHILDREN")
                            return "儿童票"
                    }
                },
                {name: "价格", field: "price", width: "10%"},
                {name: "数量", field: "number", width: "10%"}
            ],
            data: data
        });
    };
    var getTicketBySpotIdData = function (spotId) {
        $.ajax({
            url:getServer()+"/flea/hclv/spotTicket/selectBySpotId.htmls",
            method:'post',
            data:{'spotId':spotId},
            success:function(data){
                 var data=data.data.curPageData;
                initTicketGrid(data);
            }
        });
    }
        var editSpotTicket = function(row) {
            $("#spotName1").val(spotName);
            getTicketType(row.type);
            var $form = $("#spotTicketForm");
            Tool.deserialize($form, row);
        };


        var getQueryParam = function(){
            return {
                spotName: $("#spotName").val(),
                level: $("#queryLevel").val(),
                province: $("#queryProvince").val(),
                area: $("#queryZone").val(),
                city: $("#city").val()
            };
        };

        var deleteBySelectIds = function(){
            var gdata = Grid.getGrid("DemoGirdDivId");
            var selectRows = gdata.getSelectedRow();
            if(null!=selectRows){
                Util.confirm("是否要删除", function() {

                    var ids = [];

                    $.each(selectRows,function( index, selectRow ) {
                        ids.push(selectRow.id);
                    });

                    $.ajax({
                        url:getServer()+"/flea/hclv/spot/deleteByIds.htmls",
                        method:'post',
                        data:{'ids':JSON.stringify(ids)},
                        success:function(data){
                            initGrid(null);
                            Util.alert(data.message);

                        }
                    });

                }, function() {

                });
            }else{
                Util.alert('请选择要删除的数据！');
            }
        };

    var slidebar ={};
    var editSpot = function(data){
    	slidebar = Slidebar({
            size:"lg",
    		url : getServer() + "/static/app/spots/spotsInfos/views/editSpots.html",
//    		close:true,
    		afterLoad : function($Panel) {
                var uploadFile = [];
                var $form = $("#spotForm");
                
                initFileUpload(uploadFile);
                //会显图片
                if(data!=null){
                    getAllPics(data.id);
                }
                getLevelData(data == null ? null : data.level);
                provinceSelect(null==data?null:data.province);
                getAddressById(null==data?null:data.id);
                //处理图片
                //todo 图片上传后立刻显示，所有图片的展示
                // getImagesById(data.id);
                Tool.deserialize($form, data);

                //绑定保存按钮
                $("#btnSave").on("click",function() {
                    saveOrUpdateSpot(uploadFile);
                });
    		}
    	})
    };
    //添加门票按钮
        var addTicket = function(id){
            ticketSlidebar = Slidebar({
                size: "lg",
                url: getServer() + "/static/app/spots/spotsTicket/views/editSpotsTicket1.html",
//                close: true,
                afterLoad: function ($Panel) {
                    $("#spotName1").val(spotName);
                    getTicketType(null);
                    getTicketBySpotIdData(id);
                    $("#btnSave").on("click",function() {
                        saveOrUpdateSpotTicket(id);
                    });
                }
            });
        };
        var saveOrUpdateSpotTicket = function (id) {
            // console.log(id);
            var model = Tool.serialize("spotTicketForm"); //序列化表单1
            $.ajax({
                url:getServer()+"/flea/hclv/spotTicket/saveOrUpdateSpotTicket.htmls",
                data:
                    {"model":JSON.stringify(model),'spotId':id},
                success:function(data){
                    Util.alert("操作成功");
                    getTicketBySpotIdData(id);
                    Tool.deserialize($("#ticketGird"), null);
                    // ticketGrid.refresh();
                }
            });
        };
        //获取门票类型
        var getTicketType = function (type) {
            $.ajax({
                url:getServer()+"/flea/dict/initTree.htmls",
                async:false,
                data:{'dictCode':'D_SPOT_TICKET_TYPE'},
                success:function(data){
                    var types = data;
                    queryTicketTypeSelect(types,type);
                }
            });
        };
        var queryTicketTypeSelect = function(types,initType){
            inputSelect.dropCache();
            inputSelect({
                id:"ticketTypeName",
                key : {
                    id : "dictCode",
                    name : "dictName",
                    data : "data"
                },
                data :types,
                searchAble : true,
                initData:[initType],
                callback : function(id, data) {
                    var str = "";
                    $.each(data, function(i, n){
                        str += n.dictCode;
                    });
                    $("#type").val(str);
                }
            });
        };
        var getImagesById = function (id) {
            if(id!=null){
                $.ajax({
                    url:"",
                    data:{"spotId":id},
                    success:function (data) {

                    }
                });
            }
        };

        var initFileUpload = function(uploadFile){
            var settings = {
                placeAt:"multiFileUpload",
                onUploadSuccess:function(file){
                    uploadFile.push({'resouceId':file.swordFileId,'path':file.swordFilePath});
                    // console.log(file)
                },
                onDeleteSavedFile:function(file){
                    // console.log(file)
                }
            };
            var MFUpload = MFU.init(settings);
        };

    var getAddressById = function (spotId) {
        $.ajax({
            url:getServer()+'/flea/hclv/address/findByReUUid.htmls',
            data:{'uuid':spotId},
            async: false,
            success:function(data){
                var address = data.data;
                var $form = $("#spotForm");
                Tool.deserialize($form, address);
                if(null!=address){
                	
                	$('#addRessId').val(address.id);
                    initForUpdateSelect(address.province,address.city,address.area);
                }

            }
        });
    };
    var initForUpdateSelect = function(province,city,area){
            provinceSelect(province);
            getCity(province,city);
            getZone(city,area);
    };
    var provinceSelect = function(initProvice){
            inputSelect.dropCache();
            inputSelect({
                id:"provinceName",
                key : {
                    id : "dictCode",
                    name : "dictName",
                    data : "data"
                },
                data :provinces,
                simpleData : true,
                //启用文本搜索
                initData:[initProvice],
                searchAble : false,
                //选择之后回调方法：id，选择的id数组，data，选择的数据数组
                callback : function(id, data) {
                    var str = "";
                    $.each(data, function(i, n){
                        str += n['dictCode'];
                    });
                    getCity(str);
                    $("#province").val(str);
                }
            });
    };
        var queryProvinceSelect = function(initProvice){
            inputSelect.dropCache();
            inputSelect({
                id:"queryProvinceName",
                key : {
                    id : "dictCode",
                    name : "dictName",
                    data : "data"
                },
                data :provinces,
                simpleData : true,
                //启用文本搜索
                initData:[initProvice],
                searchAble : false,
                //选择之后回调方法：id，选择的id数组，data，选择的数据数组
                callback : function(id, data) {
                    var str = "";
                    $.each(data, function(i, n){
                        str += n['dictCode'];
                    });
                    queryCity(str);
                    $("#queryProvince").val(str);
                }
            });
        };
    var getProvince = function(){
            $.ajax({
                async:false,
                url:getServer()+"/flea/hclv/getProvinces.htmls",
                success:function(data){
                    provinces = data.data;
                }
            });
    };

    var getCity = function(pcode,initCity){
            $.ajax({
                url:getServer()+"/flea/hclv/getCity.htmls",
                data:{'pcode':pcode},
                success:function(data){
                    citys = data.data;
                    citySelect(citys,initCity);
                }
            });
    };
        var queryCity = function(pcode,initCity){
            $.ajax({
                url:getServer()+"/flea/hclv/getCity.htmls",
                data:{'pcode':pcode},
                success:function(data){
                    citys = data.data;
                    queryCitySelect(citys,initCity);
                }
            });
        };
    var citySelect = function(citys,initCity){
            inputSelect.dropCache();
            inputSelect({
                id:"cityName",
                key : {
                    id : "dictCode",
                    name : "dictName",
                    data : "data"
                },
                data :citys,
                simpleData : true,
                initData:[initCity],
                searchAble : true,
                callback : function(id, data) {
                    var str = "";
                    $.each(data, function(i, n){
                        str += n['dictCode'];
                    });
                    getZone(str);
                    $("#city").val(str);

                }
            });
    };
        var queryCitySelect = function(citys,initCity){
            inputSelect.dropCache();
            inputSelect({
                id:"queryCityName",
                key : {
                    id : "dictCode",
                    name : "dictName",
                    data : "data"
                },
                data :citys,
                simpleData : true,
                initData:[initCity],
                searchAble : true,
                callback : function(id, data) {
                    var str = "";
                    $.each(data, function(i, n){
                        str += n['dictCode'];
                    });
                    queryZone(str);
                    $("#queryCity").val(str);

                }
            });
        };
    var zoneSelect = function(zones,initZone){
            inputSelect.dropCache();
            inputSelect({
                id:"zoneName",
                key : {
                    id : "dictCode",
                    name : "dictName",
                    data : "data"
                },
                data :zones,
                searchAble : true,
                initData:[initZone],
                callback : function(id, data) {
                    var str = "";
                    $.each(data, function(i, n){
                        str += n.dictCode;
                    });
                    $("#area").val(str);
                }
            });
    };
        var queryZoneSelect = function(zones,initZone){
            inputSelect.dropCache();
            inputSelect({
                id:"queryZoneName",
                key : {
                    id : "dictCode",
                    name : "dictName",
                    data : "data"
                },
                data :zones,
                searchAble : true,
                initData:[initZone],
                callback : function(id, data) {
                    var str = "";
                    $.each(data, function(i, n){
                        str += n.dictCode;
                    });
                    $("#queryZone").val(str);
                }
            });
        };
    var getZone = function(pcode,initZone){
            $.ajax({
                url:getServer()+"/flea/hclv/getZone.htmls",
                data:{'pcode':pcode},
                success:function(data){
                    var zones = data.data;
                    zoneSelect(zones,initZone);
                }
            });
    };
        var queryZone = function(pcode,initZone){
            $.ajax({
                url:getServer()+"/flea/hclv/getZone.htmls",
                data:{'pcode':pcode},
                success:function(data){
                    var zones = data.data;
                    queryZoneSelect(zones,initZone);
                }
            });
        };
    //获取景区等级
    var getLevelData = function (level) {
        $.ajax({
            url:getServer()+"/flea/dict/initTree.htmls",
            async:false,
            data:{'dictCode':'D_SPOT_LEVEL'},
            success:function(data){
                var levels = data;
                levelSelect(levels,level);
            }
        });
    };
        var queryLevelData = function (level) {
            $.ajax({
                url:getServer()+"/flea/dict/initTree.htmls",
                async:false,
                data:{'dictCode':'D_SPOT_LEVEL'},
                success:function(data){
                    var levels = data;
                    queryLevelSelect(levels,null);
        }
            });
        };

    //初始化等级下拉框
    var levelSelect = function(leves,initLevel){
            inputSelect.dropCache();
            inputSelect({
                id:"levelName",
                key : {
                    id : "dictCode",
                    name : "dictName",
                    data : "data"
                },
                data :leves,
                searchAble : true,
                initData:[initLevel],
                callback : function(id, data) {
                    var str = "";
                    $.each(data, function(i, n){
                        str += n.dictCode;
                    });
                    $("#level").val(str);
                }
            });
    };
        var queryLevelSelect = function(leves,initLevel){
            inputSelect.dropCache();
            inputSelect({
                id:"queryLevelName",
                key : {
                    id : "dictCode",
                    name : "dictName",
                    data : "data"
                },
                data :leves,
                searchAble : true,
                initData:[initLevel],
                callback : function(id, data) {
                    var str = "";
                    $.each(data, function(i, n){
                        str += n.dictCode;
                    });
                    $("#queryLevel").val(str);
                }
            });
        };

    var saveOrUpdateSpot = function(uploadFile){

        var model = Tool.serialize("spotForm"); //序列化表单1
        // console.log(model);
        $.ajax({
            url:getServer()+"/flea/hclv/spot/saveOrUpdateSpot.htmls",
            data:
                {"model":JSON.stringify(model),'files':JSON.stringify(uploadFile)},
            success:function(data){
                Util.alert("操作成功");
                grid.refresh();
                slidebar.close();
            }
        });

    };
        var getAllPics = function(uuid){
            // console.log(uuid);
            $.ajax({
                url:getServer()+'/flea/hclv/resRelation/getFilePathByUuid.htmls',
                data:{'uuid':uuid},
                success:function(data){
                    // console.log(data);
                    var viewerSettings = {
                        placeAt:'dowebok',
                        fileLists:data
                    };
                    initPicViewer(viewerSettings);
                    var viewer = new Viewer(document.getElementById('dowebok'), {url: 'data-original'});
                }
            });
        };
        var initPicViewer = function(settings){
            var id = settings.placeAt;
            var fileList = settings.fileLists;
            for(var i=0;i<fileList.length;i++){
                var file = fileList[i];
                $('#'+id).append('<li><img data-original='+Properties.URL_FILE_SERVER_URL+file.path+' src="'+Properties.URL_FILE_SERVER_URL+file.path+'" alt="sss"></li>');
            }
        }

    var init =function () {
        initGrid();
        queryLevelData(null);
        getProvince();
        queryProvinceSelect(null);

    };

    return {
        init:init
    }
});